package lib

import (
	//"database/sql"
	"flag"
	"fmt"
	libs "github.com/e421083458/golang_common/lib"
	dlog "github.com/e421083458/golang_common/log"
	//"github.com/e421083458/gorm"
	//"github.com/spf13/viper"
	"log"
	"os"
	"strings"
	"time"
)


//模块初始化
func InitModule(configPath string, modules []string) error {
	conf := flag.String("config", configPath, "input config file like ./conf/dev/")
	flag.Parse()
	if *conf == "" {
		flag.Usage()
		os.Exit(1)

	}

	log.Println("------------------------------------------------------------------------")
	log.Printf("[INFO]  config=%s\n", *conf)
	log.Printf("[INFO] %s\n", " start loading resources.")

	// 设置ip信息，优先设置便于日志打印
	ips := libs.GetLocalIPs()
	if len(ips) > 0 {
		libs.LocalIP = ips[0]
	}

	// 解析配置文件目录
	if err := libs.ParseConfPath(*conf); err != nil {
		return err
	}

	//初始化配置文件
	if err := libs.InitViperConf(); err != nil {
		return err
	}

	// 加载base配置
	if libs.InArrayString("base", modules) {
		if err := InitBaseConf(libs.GetConfPath("base")); err != nil {
			fmt.Printf("[ERROR] %s%s\n", time.Now().Format(libs.TimeFormat), " InitBaseConf:"+err.Error())
		}
	}

	// 加载redis配置
	if libs.InArrayString("redis", modules) {
		if err := libs.InitRedisConf(libs.GetConfPath("redis_map")); err != nil {
			fmt.Printf("[ERROR] %s%s\n", time.Now().Format(libs.TimeFormat), " InitRedisConf:"+err.Error())
		}
	}

	// 加载mysql配置并初始化实例
	if libs.InArrayString("mysql", modules) {
		if err := libs.InitDBPool(libs.GetConfPath("mysql_map")); err != nil {
			fmt.Printf("[ERROR] %s%s\n", time.Now().Format(libs.TimeFormat), " InitDBPool:"+err.Error())
		}
	}

	// 设置时区
	if location, err := time.LoadLocation(libs.ConfBase.TimeLocation); err != nil {
		return err
	} else {
		libs.TimeLocation = location
	}

	log.Printf("[INFO] %s\n", " success loading resources.")
	log.Println("------------------------------------------------------------------------")
	return nil
}

type BaseConf  = libs.BaseConf

//base 配置
func InitBaseConf(path string) error {
	libs.ConfBase = &BaseConf{}
	err := libs.ParseConfig(path, libs.ConfBase)
	if err != nil {
		return err
	}

	if libs.ConfBase.DebugMode == "" {
		if libs.ConfBase.Base.DebugMode != "" {
			libs.ConfBase.DebugMode = libs.ConfBase.Base.DebugMode
		} else {
			libs.ConfBase.DebugMode = "debug"
		}
	}
	if libs.ConfBase.TimeLocation == "" {
		if libs.ConfBase.Base.TimeLocation != "" {
			libs.ConfBase.TimeLocation = libs.ConfBase.Base.TimeLocation
		} else {
			libs.ConfBase.TimeLocation = "Asia/Chongqing"
		}
	}
	if libs.ConfBase.Log.Level == "" {
		libs.ConfBase.Log.Level = "trace"
	}

	//更换日志写出目录
	dateTime := time.Now().Format("2006/01/02 15:04:05")
	dateTime = strings.Split(dateTime," ")[0]
	if strings.Contains(libs.ConfBase.Log.FW.LogPath,"[date]"){
		libs.ConfBase.Log.FW.LogPath= strings.Replace(libs.ConfBase.Log.FW.LogPath, "[date]", dateTime, -1)
	}
	if strings.Contains(libs.ConfBase.Log.FW.WfLogPath,"[date]"){
		libs.ConfBase.Log.FW.WfLogPath= strings.Replace(libs.ConfBase.Log.FW.WfLogPath, "[date]", dateTime, -1)
	}

	//配置日志
	logConf := dlog.LogConfig{
		Level: libs.ConfBase.Log.Level,
		FW: dlog.ConfFileWriter{
			On:              libs.ConfBase.Log.FW.On,
			LogPath:         libs.ConfBase.Log.FW.LogPath,//日志路径
			RotateLogPath:   libs.ConfBase.Log.FW.RotateLogPath,//旋转日志路径
			WfLogPath:       libs.ConfBase.Log.FW.WfLogPath,
			RotateWfLogPath: libs.ConfBase.Log.FW.RotateWfLogPath,
		},
		CW: dlog.ConfConsoleWriter{
			On:    libs.ConfBase.Log.CW.On,
			Color: libs.ConfBase.Log.CW.Color,
		},
	}
	if err := dlog.SetupDefaultLogWithConf(logConf); err != nil {
		panic(err)
	}
	dlog.SetLayout("2006-01-02T15:04:05.000")
	return nil
}


//公共销毁函数
func Destroy() {
	log.Println("------------------------------------------------------------------------")
	log.Printf("[INFO] %s\n", " start destroy resources.")
	CloseDB()
	dlog.Close()
	log.Printf("[INFO] %s\n", " success destroy resources.")
}


func CloseDB() error {
	for _, dbpool := range libs.DBMapPool {
		dbpool.Close()
	}
	for _, dbpool := range libs.GORMMapPool {
		dbpool.Close()
	}
	return nil
}